from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_categories():

    # 1.定义有序字典
    categories = OrderedDict()
    #2查询所有频道信息
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 3.对所有频道进行遍历
    for channel in channels:
        # 获4取当前频道的group_id（获取当前频道）
        group_id = channel.group_id  # 当前组
        #5.判断当期那频道是否在有序字典中
        if group_id not in categories:
            categories[group_id] = {'channels': [],
                                    'sub_cats': []}

        #6.后去当期那的分类，将当前分类添加到频道中channels
        cat1 = channel.category  # 当前频道的类别

        # 追加当前频道
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })
        # 构建当前类别的子类别
        # 7.通过当前分之获取子分类及子子分类添加到sub_cats中
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    return categories